<?php
namespace App\Middleware;

use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;

class TrimStringsParameterProcessing
{
    private $except = [];

    public function __invoke(Request $request, RequestHandler $handler): Response
    {
        $params = $request->getQueryParams();
        foreach ($params as $k => $v) {
            $params[$k] = $this->trimValue($v);
        }
        $request = $request->withQueryParams($params);

        $params = $request->getParsedBody();
        foreach ($params as $k => $v) {
            $params[$k] = $this->trimValue($v);
        }
        $request = $request->withParsedBody($params);

        $response = $handler->handle($request);

        return $response;
    }

    private function trimValue($value)
    {
        if (is_array($value)) {
            return $this->trimArray($value);
        }
        return trim($value);
    }

    private function trimArray(array $value)
    {
        foreach ($value as $k => $v) {
            $value[$k] = $this->trimValue($v);
        }
        return $value;
    }
}
